

import { Component, OnInit, ViewChild, TemplateRef, ChangeDetectorRef } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { finalize } from 'rxjs/operators';

import { CustomerServiceService } from '@core/services/http/system/customer-service.service';
import { OptionsInterface, SearchCommonVO } from '@core/services/types';
import { ValidatorsService } from '@core/services/validators/validators.service';
import { MyTableConfig } from '@shared/components/ant-table/ant-table.component';
import { PageHeaderType } from '@shared/components/page-header/page-header.component';
import { ServiceData } from '@shared/models/service.models';
import { NzTreeNodeOptions } from 'ng-zorro-antd/core/tree';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzTableQueryParams } from 'ng-zorro-antd/table';

@Component({
  selector: 'app-service',
  templateUrl: './service.component.html',
  styleUrls: ['./service.component.less']
})

export class ServiceComponent implements OnInit {
  @ViewChild('operationTpl', { static: true }) operationTpl!: TemplateRef<any>;

  deptNodes: NzTreeNodeOptions[] = [];
  addEditForm!: FormGroup;
  isEdit = false;
  dataList: ServiceData[] = [];
  tableConfig!: MyTableConfig;
  serviceTypeOptions: OptionsInterface[] = [
    {
      label: 'End User Service',
      value: 'End User Service'
    },
    {
      label: 'Front End',
      value: 'Front End'
    },
    {
      label: 'Back End',
      value: 'Back End'
    },
    {
      label: 'IT Management',
      value: 'IT Management'
    },
    {
      label: 'Reporting',
      value: 'Reporting'
    },
    {
      label: 'IT Operational',
      value: 'IT Operational'
    },
    {
      label: 'Demonstration',
      value: 'Demonstration'
    },
    {
      label: 'Project',
      value: 'Project'
    },
    {
      label: 'Training',
      value: 'Training'
    },
    {
      label: 'Other',
      value: 'Other'
    },
    {
      label: 'Underpinning Contract',
      value: 'Underpinning Contract'
    }
  ];
  criticalityOptions: OptionsInterface[] = [
    {
      label: '3 normal',
      value: '3 normal'
    }
  ];
  pageHeaderInfo: Partial<PageHeaderType> = {
    title: '账号管理(数据库每10分钟从备份恢复一次)',
    breadcrumb: ['首页', '用户管理', '账号管理']
  };
  constructor(private cdr: ChangeDetectorRef, private validatorsService: ValidatorsService, private dataService: CustomerServiceService, private fb: FormBuilder, public message: NzMessageService) {}

  ngOnInit(): void {
    this.initTable();
  }

  getDataList(e?: NzTableQueryParams): void {
    this.tableConfig.loading = true;
    const params: SearchCommonVO<any> = {
      pageSize: this.tableConfig.pageSize!,
      pageNum: e?.pageIndex || this.tableConfig.pageIndex!,
    };
    this.dataService
      .getServiceList(params)
      .pipe(
        finalize(() => {
          this.tableLoading(false);
        })
      )
      .subscribe(data => {
        const { list, total, pageNum } = data;
        this.dataList = [...list];
        this.tableConfig.total = total!;
        this.tableConfig.pageIndex = pageNum!;
        this.tableLoading(false);
      });
  }

  reloadTable(): void {
    this.message.info('刷新成功');
    this.getDataList();
  }
  // 触发表格变更检测
  tableChangeDectction(): void {
    // 改变引用触发变更检测。
    this.dataList = [...this.dataList];
    this.cdr.detectChanges();
  }
  changePageSize(e: number): void {
    this.tableConfig.pageSize = e;
  }
  tableLoading(isLoading: boolean): void {
    this.tableConfig.loading = isLoading;
    this.tableChangeDectction();
  }
  add(): void {
    this.isEdit = true;
    const Servedata: NzSafeAny = {};
    this.initForm(Servedata);
  }

  edit(id: number): void {
    this.dataService.getServiceDetail(id)
      .pipe(
        finalize(() => {
          this.tableLoading(false);
        })
      )
      .subscribe(data => {
        this.initForm(data);
        this.isEdit = true;
        this.getDataList();
      });
  }

  // init form
  initForm(param: ServiceData): void {
    this.addEditForm = this.fb.group({
      id: param.id,
      icon: param.icon,
      name: [param.name, [Validators.required, this.validatorsService.passwordValidator()]],
      parentId: param.validId,
      validId: [param.validId, [Validators.required]],
      typeId: param.typeId,
      criticality: param.criticality,
      internalNote: param.internalNote,
      externalNote: param.externalNote,
      comment: param.comment
    });
  }
  private initTable(): void {
    this.tableConfig = {
      showCheckbox: true,
      headers: [
        {
          title: '名称',
          field: 'name',
          width: 100
        },
        {
          title: '内部备注',
          width: 100,
          field: 'available'
        },
        {
          title: '外部备注',
          width: 70,
          field: 'sex',
          pipe: 'sex'
        },
        {
          title: '有效性',
          width: 100,
          field: 'mobile'
        },
        {
          title: '创建人',
          width: 100,
          field: 'email'
        },
        {
          title: '最后登录时间',
          width: 120,
          field: 'lastLoginTime',
          pipe: 'date:yyyy-MM-dd HH:mm'
        },
        {
          title: '创建时间',
          width: 100,
          field: 'createTime',
          pipe: 'date:yyyy-MM-dd HH:mm'
        },
        {
          title: '电话',
          width: 100,
          field: 'telephone'
        },
        {
          title: '',
          width: 100,
          field: 'departmentName'
        },
        {
          title: '操作',
          tdTemplate: this.operationTpl,
          width: 150,
          fixed: true
        }
      ],
      total: 0,
      loading: true,
      pageSize: 10,
      pageIndex: 1
    };
  }
}
